<template>
  <div>
    <div style=" width: 900px;border: 1px solid #ccc">
      <Toolbar
        style="border-bottom: 1px solid #ccc"
        :editor="editorRef"
        :defaultConfig="toolbarConfig"
        mode="default"
      />
      <Editor
        v-model="content"
        style="height: 500px; overflow-y: hidden"
        :defaultConfig="editorConfig"
        mode="default"
        @onCreated="handleCreated"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import "@wangeditor/editor/dist/css/style.css"; // 引入 css
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import { ref, shallowRef, defineProps, defineEmits, watch } from "vue";
import { getToken } from "@/utils/auth";

// 图片根路径
const BaseImgUrl = import.meta.env.VITE_APP_API_URL + "/api/upload/add";
console.log(BaseImgUrl);

const headers = { Authorization: getToken() };
const imgBaseUrl = import.meta.env.VITE_IMG_URL;

const props = defineProps({
  modelValue: {
    type: String,
  },
});
const emit = defineEmits(["update:modelValue"]);

const editorRef = shallowRef();
// 内容 HTML
const content = ref("");
watch(content, (newVal) => {
  emit("update:modelValue", newVal);
});

// 数据回显
watch(
  () => props.modelValue,
  (newVal) => {
    content.value = newVal!;
  }
);

const toolbarConfig = {};
type InsertFnType = (url: string, alt: string, href: string) => void;
const editorConfig = {
  placeholder: "请输入内容...",
  MENU_CONF: {
    // 上传图片
    uploadImage: {
      fieldName: "file",
      server: BaseImgUrl,
      headers,
      customInsert(res: any, insertFn: InsertFnType) {
        // TS 语法

        // console.log(1111, res);

        insertFn(imgBaseUrl + res.data.url, "", "");

        // customInsert(res, insertFn) {                  // JS 语法
        // res 即服务端的返回结果

        // 从 res 中找到 url alt href ，然后插入图片
        // insertFn(url, alt, href)
      },
    },
  },
};

const handleCreated = (editor: any) => {
  editorRef.value = editor; // 记录 editor 实例，重要！
};
</script>

<style scoped lang="less"></style>
